import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  NavBar,
  List,
  SwipeAction,
  Toast,
  Button,
  Dialog,
  Form,
  Input,
  Switch,
  Popup
} from 'antd-mobile';
import { AddOutline } from 'antd-mobile-icons';
import './Address.css';

const Address = () => {
  const navigate = useNavigate();
  const [addresses, setAddresses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showAddressForm, setShowAddressForm] = useState(false);
  const [editingAddress, setEditingAddress] = useState(null);
  const [form] = Form.useForm();

  // 加载地址数据
  useEffect(() => {
    setLoading(true);

    // 检查用户是否登录
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo) {
      navigate('/login');
      return;
    }

    // 从本地存储获取地址数据
    const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');

    if (storedAddresses.length === 0) {
      // 如果没有地址数据，添加一些默认数据
      const defaultAddresses = [
        {
          id: 1,
          name: '张三',
          phone: '13800138000',
          province: '广东省',
          city: '深圳市',
          district: '南山区',
          address: '科技园南路XX号',
          isDefault: true
        },
        {
          id: 2,
          name: '李四',
          phone: '13900139000',
          province: '广东省',
          city: '广州市',
          district: '天河区',
          address: '天河路XX号',
          isDefault: false
        }
      ];

      localStorage.setItem('addresses', JSON.stringify(defaultAddresses));
      setAddresses(defaultAddresses);
    } else {
      setAddresses(storedAddresses);
    }

    setLoading(false);
  }, [navigate]);

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 添加地址
  const addAddress = () => {
    setEditingAddress(null);
    form.resetFields();
    setShowAddressForm(true);
  };

  // 编辑地址
  const editAddress = (address) => {
    setEditingAddress(address);
    form.setFieldsValue({
      name: address.name,
      phone: address.phone,
      province: address.province,
      city: address.city,
      district: address.district,
      address: address.address,
      isDefault: address.isDefault
    });
    setShowAddressForm(true);
  };

  // 删除地址
  const deleteAddress = (id) => {
    Dialog.confirm({
      content: '确认删除该地址吗？',
      onConfirm: () => {
        const updatedAddresses = addresses.filter(addr => addr.id !== id);

        // 如果删除的是默认地址，且还有其他地址，则将第一个地址设为默认
        if (addresses.find(addr => addr.id === id)?.isDefault && updatedAddresses.length > 0) {
          updatedAddresses[0].isDefault = true;
        }

        setAddresses(updatedAddresses);
        localStorage.setItem('addresses', JSON.stringify(updatedAddresses));

        Toast.show({
          icon: 'success',
          content: '删除成功',
        });
      },
    });
  };

  // 设为默认地址
  const setDefaultAddress = (id) => {
    const updatedAddresses = addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === id
    }));

    setAddresses(updatedAddresses);
    localStorage.setItem('addresses', JSON.stringify(updatedAddresses));

    Toast.show({
      icon: 'success',
      content: '设置成功',
    });
  };

  // 提交地址表单
  const onFinish = (values) => {
    if (editingAddress) {
      // 编辑地址
      const updatedAddresses = addresses.map(addr => {
        if (addr.id === editingAddress.id) {
          return { ...addr, ...values };
        }

        // 如果设置了新的默认地址，则其他地址不为默认
        if (values.isDefault && addr.id !== editingAddress.id) {
          return { ...addr, isDefault: false };
        }

        return addr;
      });

      setAddresses(updatedAddresses);
      localStorage.setItem('addresses', JSON.stringify(updatedAddresses));

      Toast.show({
        icon: 'success',
        content: '修改成功',
      });
    } else {
      // 添加新地址
      const newAddress = {
        ...values,
        id: Date.now(),
      };

      // 如果设置了新的默认地址，则其他地址不为默认
      let newAddresses;
      if (values.isDefault) {
        newAddresses = addresses.map(addr => ({
          ...addr,
          isDefault: false
        }));
      } else {
        newAddresses = [...addresses];
      }

      // 如果这是第一个地址，自动设为默认
      if (newAddresses.length === 0) {
        newAddress.isDefault = true;
      }

      newAddresses.push(newAddress);
      setAddresses(newAddresses);
      localStorage.setItem('addresses', JSON.stringify(newAddresses));

      Toast.show({
        icon: 'success',
        content: '添加成功',
      });
    }

    setShowAddressForm(false);
  };

  return (
    <div className="address-page">
      <NavBar onBack={back}>收货地址</NavBar>

      <div className="address-list-container">
        {loading ? (
          <div className="loading-container">
            <div className="loading-spinner">加载中...</div>
          </div>
        ) : addresses.length === 0 ? (
          <div className="empty-address">
            <p>暂无收货地址</p>
            <Button color='primary' onClick={addAddress}>添加地址</Button>
          </div>
        ) : (
          <List className="address-list">
            {addresses.map(address => (
              <SwipeAction
                key={address.id}
                rightActions={[
                  {
                    key: 'delete',
                    text: '删除',
                    color: 'danger',
                    onClick: () => deleteAddress(address.id)
                  }
                ]}
              >
                <List.Item
                  onClick={() => editAddress(address)}
                  arrow
                  extra={address.isDefault && <span className="default-tag">默认</span>}
                >
                  <div className="address-item">
                    <div className="address-header">
                      <span className="address-name">{address.name}</span>
                      <span className="address-phone">{address.phone}</span>
                    </div>
                    <div className="address-content">
                      {`${address.province}${address.city}${address.district}${address.address}`}
                    </div>
                  </div>
                </List.Item>
              </SwipeAction>
            ))}
          </List>
        )}
      </div>

      <div className="address-add-button">
        <Button
          color='primary'
          onClick={addAddress}
          block
          icon={<AddOutline />}
        >
          新增收货地址
        </Button>
      </div>

      {/* 地址表单弹窗 */}
      <Popup
        visible={showAddressForm}
        onMaskClick={() => setShowAddressForm(false)}
        position='bottom'
        bodyStyle={{ height: '80vh' }}
      >
        <div className="address-form-container">
          <NavBar
            onBack={() => setShowAddressForm(false)}
            className="form-navbar"
          >
            {editingAddress ? '编辑地址' : '新增地址'}
          </NavBar>

          <Form
            form={form}
            layout='horizontal'
            mode='card'
            onFinish={onFinish}
            footer={
              <Button block type='submit' color='primary' size='large'>
                保存
              </Button>
            }
          >
            <Form.Item
              name='name'
              label='收货人'
              rules={[{ required: true, message: '请输入收货人姓名' }]}
            >
              <Input placeholder='请输入姓名' />
            </Form.Item>

            <Form.Item
              name='phone'
              label='手机号码'
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
              ]}
            >
              <Input placeholder='请输入手机号码' />
            </Form.Item>

            <Form.Item
              name='province'
              label='省份'
              rules={[{ required: true, message: '请输入省份' }]}
            >
              <Input placeholder='请输入省份' />
            </Form.Item>

            <Form.Item
              name='city'
              label='城市'
              rules={[{ required: true, message: '请输入城市' }]}
            >
              <Input placeholder='请输入城市' />
            </Form.Item>

            <Form.Item
              name='district'
              label='区县'
              rules={[{ required: true, message: '请输入区县' }]}
            >
              <Input placeholder='请输入区县' />
            </Form.Item>

            <Form.Item
              name='address'
              label='详细地址'
              rules={[{ required: true, message: '请输入详细地址' }]}
            >
              <Input placeholder='请输入详细地址，如街道、小区、楼栋号、单元室等' />
            </Form.Item>

            <Form.Item
              name='isDefault'
              label='设为默认地址'
              valuePropName='checked'
            >
              <Switch />
            </Form.Item>
          </Form>
        </div>
      </Popup>
    </div>
  );
};

export default Address; 